/**
 * @file 订单详情-百度地图
 * @author sunlife
 * @date 2020/08/17 19:03:40
 */

layui.define(['layer', '$http', 'zmnUtils', 'NP'], function (exports) {
    var $ = layui.$;
    var layer = layui.layer;
    var $http = layui.$http;
    var zmnUtils = layui.zmnUtils;
    var NP = layui.NP;

    var ACTIVE_CLASS = 'layui-btn-primary';
    var STROKE_COLOR = "#ff0000";

    let POSITION_TYPE_CONSTS = {
        ORDER: 1,
        START: 2,
        VISIT: 3,
        DEPOSIT_PAY: 4,
        MASTER_PAY: 5,
        COMPLETE: 6
    };

    /**
     * 获取多边形
     * @param points 点集
     * @returns {o.Polygon|t|r.Polygon|Polygon}
     */
    function getPolygon(points) {
        return new BMap.Polygon(points, {
            strokeColor: STROKE_COLOR,
            strokeWeight: 2,
            strokeOpacity: 0.5,
            enableClicking: false,
            enableMassClear: true
        });
    }

    function MapCacha(map) {
        this._map = map;
        this._list = [];
        this._pointArray = [];

        this.add = function (item) {
            var self = this;
            var data = self._list;
            if (zmnUtils.isArray(data)) {
                this._list.push(item);
            }

            this.render();
        }

        this.clear = function () {
            this.render(true);
            this._list = [];
            this._pointArray = [];
        }
    }

    function PolygonsCacha (map) {
        MapCacha.call(this, map);
    }

    PolygonsCacha.prototype.render = function (remove) {
        var self = this;
        var data = this._list;

        if (!zmnUtils.isArray(data)) {
            return;
        }

        data.forEach(function (polygons) {
            polygons.forEach(function (ply) {
                if (remove) {
                    self._map.removeOverlay(ply);
                } else {
                    self._map.addOverlay(ply);
                    self._pointArray = self._pointArray.concat(ply.getPath());
                }
            });
        });

        if (!remove && self._pointArray.length) {
            self._map.setViewport(self._pointArray);
        }
    };


    function MarkersCacha(map) {
        MapCacha.call(this, map)
    }

    MarkersCacha.prototype.render = function (remove) {
        var self = this;
        var data = this._list;

        if (!zmnUtils.isArray(data)) {
            return;
        }

        data.forEach(function (item) {
            if (remove) {
                self._map.removeOverlay(item);
            } else {
                self._map.addOverlay(item);
            }
        });
    };


    var saddressmap = {
        // 地图实例
        _map: null,

        _orderInfo: null,
        _startInfo: null,
        _visitInfo: null,
        _completeInfo: null,
        _depositPayInfo: null,
        _masterPayInfo: null,

        // 窗口 index
        _layerIndex: parent.layer.getFrameIndex(window.name),
        // 所有点集合
        _infos: new Array(),

        /**
         * 初始化地图
         */
        init: function () {
            var self = this;

            // 初始化地图
            var mapInstance = new BMap.Map("allmap");
            mapInstance.centerAndZoom(new BMap.Point(position.orderLongitude, position.orderLatitude), 15);  // 初始化地图,设置中心点坐标和地图级别
            mapInstance.enableScrollWheelZoom(true);
            self._map = mapInstance;
            self._polygons = new PolygonsCacha(mapInstance);

            if (!position.orderLongitude && !position.orderLatitude) {
                return false;
            }

            // 初始化各个点
            let orderPoint = new BMap.Point(position.orderLongitude, position.orderLatitude);
            self._orderInfo = {
                _type: POSITION_TYPE_CONSTS.ORDER,
                _point: orderPoint
            };
            self._infos.push( self._orderInfo);
            if (position.startLongitude && position.startLatitude) {
                let startPoint = new BMap.Point(position.startLongitude, position.startLatitude);
                self._startInfo = {
                    _type: POSITION_TYPE_CONSTS.START,
                    _point: startPoint,
                    _distance: position.startDistance
                };
                self._infos.push(self._startInfo);
            }
            if (position.visitLongitude && position.visitLatitude) {
                let visitPoint = new BMap.Point(position.visitLongitude, position.visitLatitude);
                self._visitInfo = {
                    _type: POSITION_TYPE_CONSTS.VISIT,
                    _point: visitPoint,
                    _distance: position.visitDistance
                };
                self._infos.push(self._visitInfo);
            }
            if (position.depositPayLongitude && position.depositPayLatitude) {
                let depositPayPoint = new BMap.Point(position.depositPayLongitude, position.depositPayLatitude);
                self._depositPayInfo = {
                    _type: POSITION_TYPE_CONSTS.DEPOSIT_PAY,
                    _point: depositPayPoint,
                    _distance: position.depositPayDistance
                };
                self._infos.push(self._depositPayInfo);
            }
            if (position.masterPayLongitude && position.masterPayLatitude) {
                let masterPayPoint = new BMap.Point(position.masterPayLongitude, position.masterPayLatitude);
                self._masterPayInfo = {
                    _type: POSITION_TYPE_CONSTS.MASTER_PAY,
                    _point: masterPayPoint,
                    _distance: position.masterPayDistance
                };
                self._infos.push(self._masterPayInfo);
            }
            if (position.completeLongitude && position.completeLatitude) {
                let completePoint = new BMap.Point(position.completeLongitude, position.completeLatitude);
                self._completeInfo = {
                    _type: POSITION_TYPE_CONSTS.COMPLETE,
                    _point: completePoint,
                    _distance: position.completeDistance
                };
                self._infos.push(self._completeInfo);
            }


            self._createSelectedMarker();

            // 添加服务范围
            // self._initServiceScope(orderWrok.cityId,2,orderWrok.showProductId, orderWrok.plat, orderWork.companyId);

            self.initEvent();

            self.initPageStyle();

            self.rezoomByPoints();
        },

        /**
         * 初始化地图相关事件
         */
        initEvent: function () {
            var self = this;

            // 设置 infoWindow 的点击事件处理函数
            window.handleBtnClick = function (type) {
                self._openinfoWindow(type);
            };

        },

        /**
         * 重新设置缩放等级
         */
        rezoomByPoints: function () {
            let self = this;

            let points = self._infos.map(info => {
                return info._point;
            });

            let view = self._map.getViewport(eval(points));
            let mapZoom = view.zoom - 1;
            let centerPoint = view.center;
            self._map.setZoom(mapZoom);
        },

        _closeDialog: function () {
            var self = this;
            // 关闭窗口
            parent.layer.close(self._layerIndex);
        },

        initPageStyle: function () {
            var self = this;
            if (self._orderInfo._infoWindow && self._orderInfo._point) {
                self._map.openInfoWindow(self._orderInfo._infoWindow, self._orderInfo._point);
            }
        },

        /**
         * 生成地图点击事件处理函数
         * @returns {Function} 地图点击事件处理函数
         * @private
         */
        _mapClick: function () {
            var self = this;
            return function (res) {
                self._selectedPoint = res.point;
                self._createSelectedMarker();
                self._getLoaction(self._selectedPoint);
                self._suggest(self._selectedPoint);
            }
        },

        /**
         *
         */
        _openinfoWindow: function(type) {
            var self = this;
            var info ;
            switch (type || 0) {
                case POSITION_TYPE_CONSTS.START:
                    info = self._startInfo;
                    break;
                case POSITION_TYPE_CONSTS.VISIT:
                    info = self._visitInfo;
                    break;
                case POSITION_TYPE_CONSTS.DEPOSIT_PAY:
                    info = self._depositPayInfo;
                    break;
                case POSITION_TYPE_CONSTS.MASTER_PAY:
                    info = self._masterPayInfo;
                    break;
                case POSITION_TYPE_CONSTS.COMPLETE:
                    info = self._completeInfo;
                    break;
                default:
                    break;
            }
            self._map.openInfoWindow(info._infoWindow, info._point);
        },
        _createPolygonList: function (pointList) {
            var self = this;
            var def = $.Deferred();

            if (
                !zmnUtils.isArray(pointList) ||
                !pointList.length
            ) {
                return [];
            }

            var overlayList = [];
            var flag = pointList.length;

            function getOverlayList () {
                return overlayList.filter(function(item) {
                    return !!item;
                });
            }

            function checkOverlayState () {
                if (overlayList.length >= flag) {
                    def.resolve(getOverlayList());
                }
            }

            pointList.forEach(function (item) {
                var data = item.mapData || '[]';
                var jsonArr = eval('(' + data + ')');

                var overlay = null;

                switch (item.mapDataType) {
                    case 1: {
                        overlay = getPolygon(jsonArr);
                        overlayList.push(overlay);
                        checkOverlayState();
                        break;
                    }

                    case 2: {
                        if (item.longitude && item.latitude && item.mapData) {
                            var point = new BMap.Point(item.longitude, item.latitude);
                            overlay = getCircle(point, item.mapData)
                            overlayList.push(overlay);
                        }

                        checkOverlayState();
                        break;
                    }

                    case 3: {
                        var boundary = new BMap.Boundary();
                        var city = item.city || '';
                        var county = item.county || '';

                        var cityName = city.replace('辖区', '')
                            .replace('辖县', '');
                        var regionName = cityName + county;

                        boundary.get(regionName, function (response) {
                            if (
                                zmnUtils.isObject(response) &&
                                zmnUtils.isArray(response.boundaries)) {
                                response.boundaries.forEach(function (item) {
                                    var overlay = getPolygon(item);
                                    overlayList.push(overlay);
                                });
                            }

                            checkOverlayState();
                        });

                        break;
                    }

                    default:
                        break;
                }
            })

            return def.promise();
        },

        /**
         * 生成服务服务范围覆盖层
         * @param cityId
         * @param serviceItemId
         * @param channelId
         * @private
         */
        // 初始化服务范围
        _initServiceScope: function (cityId, productShowType, productId, plat, companyId) {
            var self = this;

            if (!companyId){
                return;
            }

            $http.get('/area/point/list', {
                plat: plat,
                cityId: cityId,
                productId: productId,
                productShowType: productShowType,
            }).then(function (cityList) {
                if (zmnUtils.isArray(cityList) && cityList.length) {
                    var $container = $('<div></div>');
                    cityList.forEach(function(city, index) {
                        var classStr = 'layui-btn';
                        if (index !== 0) {
                            classStr += ' ' + ACTIVE_CLASS;
                        }

                        var $btn = $(
                            `<button type="button" class="${ classStr }">${ city.companyName }地图</button>`
                        );

                        $container.append(
                            $btn.on('click', function () {
                                var $this = $(this);

                                self._renderServiceScope(city.pointList);
                                $this.removeClass(ACTIVE_CLASS)
                                    .siblings()
                                    .addClass(ACTIVE_CLASS);
                            })
                        );

                        city.companyId === companyId
                            ? self._renderServiceScope(city.pointList)
                            : void(0);
                    });

                }
            })

        },

        _renderServiceScope: function (pointList) {
            var self = this;
            var polygonsCache = self._polygons;
            self._createPolygonList(pointList).then(function (data) {
                polygonsCache.clear();
                polygonsCache.add(data);
            });
        },

        _isPinitInServiceScope: function (location) {
            var self = this;
            self._saddressOptions.verifyFunc(location, function (data) {
                self._saddressOptions.callBack(data, self._selectedAddress);
                self._closeDialog();
            }, function (msg) {
                layer.msg(msg);
            });
        },

        /**
         * 创建选中 marker
         * @private
         */
        _createSelectedMarker: function () {
            var self = this;
            $.each(self._infos, function (index, info) {
                // 创建marker
                var imgName ;
                if (info._type === POSITION_TYPE_CONSTS.ORDER) {
                    imgName = 'position-1.png';
                } else {
                    imgName = 'position-2.png';
                }
                var myIcon = new BMap.Icon("/static/images/" + imgName, new BMap.Size(32, 32));

                var mkr = new BMap.Marker(info._point, {
                    enableDragging: false,
                    icon: myIcon
                });

                if (info._type === POSITION_TYPE_CONSTS.ORDER) {
                    self._createOrderInfoWindow(info);
                } else {
                    self._createDistanceInfoWindow(info);
                    mkr.addEventListener("mouseout",function(e) {
                        self._map.closeInfoWindow();
                    });
                }

                mkr.addEventListener("click",function(e) {
                    self._map.openInfoWindow(info._infoWindow, info._point);
                });
                mkr.addEventListener("mouseover",function(e) {
                    self._map.openInfoWindow(info._infoWindow, info._point);
                });

                info._marker = mkr;

                // 往地图添加marker
                self._map.addOverlay(mkr);
            });
        },

        /**
         * 创建信息面板
         * @private
         */
        _createOrderInfoWindow: function (info) {
            var self = this;

            var htmlInfo = '<div class="infoWindow">';
            if (!self._startInfo && !self._visitInfo && !self._depositPayInfo && !self._masterPayInfo && !self._completeInfo) {
                htmlInfo = '暂无可以查看的位置数据';
            } else {
                htmlInfo += '点击查看：<br>';
                if (self._startInfo) {
                    htmlInfo += "<a class='position' onclick='handleBtnClick("+ POSITION_TYPE_CONSTS.START +")'>出发位置</a><br>";
                }

                if (self._visitInfo) {
                    htmlInfo += "<a class='position' onclick='handleBtnClick("+ POSITION_TYPE_CONSTS.VISIT +")'>上门位置</a><br>";
                }

                if (self._depositPayInfo) {
                    htmlInfo += "<a class='position' onclick='handleBtnClick("+ POSITION_TYPE_CONSTS.DEPOSIT_PAY +")'>定金支付位置</a><br>";
                }

                if (self._masterPayInfo) {
                    htmlInfo += "<a class='position' onclick='handleBtnClick("+ POSITION_TYPE_CONSTS.MASTER_PAY +")'>尾款支付位置</a><br>";
                }

                if (self._completeInfo) {
                    htmlInfo += "<a class='position' onclick='handleBtnClick("+ POSITION_TYPE_CONSTS.COMPLETE +")'>完成位置</a><br>";
                }

            }
            htmlInfo += '</div>';

            var infoWindow = new BMap.InfoWindow(htmlInfo, {
                width: 0,
                height: 0,
            });

            info._infoWindow = infoWindow;
        },

        /**
         * 创建工单信息面板
         * @private
         */
        _createDistanceInfoWindow: function (info) {

            if (info._type && info._type === POSITION_TYPE_CONSTS.ORDER) {
                return false;
            }

            var self = this;
            var typeName ;
            switch (info._type || 0) {
                case POSITION_TYPE_CONSTS.ORDER:
                    typeName = '工单';
                    break;
                case POSITION_TYPE_CONSTS.START:
                    typeName = '出发';
                    break;
                case POSITION_TYPE_CONSTS.VISIT:
                    typeName = '上门';
                    break;
                case POSITION_TYPE_CONSTS.DEPOSIT_PAY:
                    typeName = '定金支付';
                    break;
                case POSITION_TYPE_CONSTS.MASTER_PAY:
                    typeName = '尾款支付';
                    break;
                case POSITION_TYPE_CONSTS.COMPLETE:
                    typeName = '完成';
                    break;
                default:
                    typeName = '';
            }
            var htmlInfo = '<div class="infoWindow">' + typeName + '距离：' + NP.divide(info._distance || 0, 1000) + 'km</div>';
            var infoWindow = new BMap.InfoWindow(htmlInfo, {
                width: 0,
                height: 0
            });

            info._infoWindow = infoWindow;
            //
            // self._map.openInfoWindow(infoWindow, info._point);
        },


    };



    /**
     * 初始化页面
     */
    function initPage () {
        saddressmap.init();
    }

    /**
     * 初始化页面事件
     */
    function initEvent () {
        // 地图关闭按钮点击事件
    }

    /**
     * 程序入口
     */
    function init () {
        initPage();
        initEvent();
    }

    init();
    exports('oms_work_position_map');
});




